package hoe;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import java.io.IOException;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Játék kiszolgáló.
 *
 * @author imruf84
 */
public class PlayServlet extends HttpServletWithUserValidator {

    @Override
    public void validateUser(HttpServletRequest request, HttpServletResponse response, User user, int requestType) throws IOException {

        // Ha a felhasználó hitelesítése nem megy akkor átirányítjuk a bejelentkező ablakhoz.
        if (null == user) {
            response.sendRedirect(HttpServer.LOGIN_PATH);
            return;
        }

        // Egyébként mehet a munka.
        // Oldalt kizárólag GET kérések esetében szolgálunk ki.
        if (requestType == HttpServer.GET_REQUEST) {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().append(
                    "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body style='font-family: Arial'>"
                    + "<div id=userNameDiv></div>"
                    + "<a href='/logout'>logout</a><br>"
                    + "<script>"
                    + ""
                    + "var handleResponse = function(responseText) {"
                    + "  if ('' == responseText) return;"
                    //+ "  console.log(responseText);"
                    + "  var response = JSON.parse(responseText);"
                    + "  for (var i in response) {"
                    + "    var o = response[i];"
                    //+ "    console.log(o);"
                    + "    switch(o['a']) {"
                    + "      case 'cm':"
                    + "        var cmb = document.getElementById('chatMsgBox');"
                    + "        cmb.innerHTML = '<b>' + o['d']['user'] + '</b>: ' + unescape(o['d']['msg']) + '<br>' + cmb.innerHTML;"
                    + "      break;"
                    + "    }"
                    + "  }"
                    + "};"
                    + ""
                    + "var lp = function() {"
                    + "  var xhrlp = new XMLHttpRequest();"
                    + "  xhrlp.responseType = 'text';"
                    + "  xhrlp.timeout = 20000;"
                    + "  xhrlp.ontimeout = function(){xhrlp.abort(); lp();};"
                    + "  xhrlp.onload = function(){handleResponse(xhrlp.responseText); lp();};"
                    + "  xhrlp.open('POST', '/play', true);"
                    + "  xhrlp.send('');"
                    + "};"
                    + "lp();"
                    + ""
                    + "var sendToServer = function(text) {"
                    + "  var xhr = new XMLHttpRequest();"
                    + "  xhr.responseType = 'text';"
                    + "  xhr.onload = function(){handleResponse(xhr.responseText);};"
                    + "  xhr.open('POST', '/play', true);"
                    + "  xhr.send(text);"
                    + "};"
                    + "</script>"
                    + "<input id='chatInput'><input id='sendChatMsgButton' type='button' value='Küld'>"
                    + "<div id='chatMsgBox'></div>"
                    + "<script>"
                    + "  var chatInput = document.getElementById('chatInput');"
                    + "  var sendChatMsgButton = document.getElementById('sendChatMsgButton');"
                    + "  var userNameDiv = document.getElementById('userNameDiv');"
                    + "  userNameDiv.innerHTML = unescape('" + UserManager.getUserBySession(request).getUserName() + "');"
                    //+ "  sendChatMsgButton.onclick = function(){sendToServer('{a:cm,d:{msg:\"'+chatInput.value+'\"}}');};"
                    + "  sendChatMsgButton.onclick = function(){sendToServer(JSON.stringify({a:'cm',d:{msg:escape(chatInput.value)}}));};"
                    + "</script>"
                    + "</body></html>"
            );
            return;
        }
        
        // POST kérés esetén szinkronizációs adatokkal van dolgunk.
        String jsonString = request.getReader().readLine();
        //System.out.println(jsonString);

        // Üres kérés esetén csak csatornát tárolunk.
        if (null == jsonString) {
            final AsyncContext ctxt = request.startAsync();
            user.storeAsyncContext(ctxt, response);
            return;
        }
        
        // Feldolgozás.
        Gson gson = new Gson();
        Map<String, Object> root = gson.fromJson(jsonString, Map.class);
        
        switch (root.get("a").toString()) {
            // Chat üzenet.
            case "cm":
                LinkedTreeMap data = (LinkedTreeMap)root.get("d");
                // Szétküldés mindenkinek.
                UserManager.sendMessageToAll("{\"a\":\"cm\",\"d\":{\"user\":\"" + user.getUserName() + "\",\"msg\":\"" + data.get("msg").toString() + "\"}}");
                break;
        }
        
        
    }

}
